package practice_3_4;
//给定一个有序整型数组, 实现二分查找
public class BinarySearch {
    public static void main(String[] args) {
        int[] nums1 = new int[]{2,3,5,7,9,12,15,17,18,22,25};
        int pos = binarySearch(nums1, 17);
        if(pos != -1){
            System.out.println("找到了，下标为：" + pos);
        }else{
            System.out.println("未找到");
        }
    }
    public static int binarySearch(int[] nums, int key){
        int left = 0;
        int right = nums.length - 1;
        while(left <= right){
            int mid = left + (right - left) / 2;
            if(nums[mid] < key){
                left = mid + 1;
            }else if(nums[mid] > key){
                right = mid - 1;
            }else{
                return mid;
            }
        }
        return -1;
    }
}
